package cn.devcat.sso.util;

import java.util.Date;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

/**
 * JWT 工具类
 * @author huhailong
 *
 */
public class JWTUtil {
	
	//设置过期时间 1周
	private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;
	
	private static final String TOKEN_PREFIX = "Bearer ";
	
	public static String sign(String username, String secret) {
		Date expireDate = new Date(System.currentTimeMillis()+EXPIRE_TIME);
		Algorithm algorithm = Algorithm.HMAC256(secret);
		String sign = JWT.create().withClaim("username", username).withExpiresAt(expireDate).sign(algorithm);
		return TOKEN_PREFIX+sign;
	}
	
	public static DecodedJWT decode(String token) {
		String trueToken = token.replace(TOKEN_PREFIX,"").trim();
		return JWT.decode(trueToken);
	}
	
	public static boolean checkToken(String token, String username, String secret) {
		String trueToken = token.replace(TOKEN_PREFIX,"").trim();
		try{
            //根据密码生成校验器
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).withClaim("username",username).build();
            //校验token
            verifier.verify(trueToken);
            return true;
        } catch (Exception e){
            return false;
        }
	}

}
